package com.yanqu.road.entity.kuang.battle;


import java.util.Comparator;
import java.util.LinkedList;
import java.util.Objects;

public class CrossKuangRankListModel {

    private Comparator<CrossKuangRank> rankSort = new CrossKuangRankSort();

    private LinkedList<CrossKuangRank> rankList = new LinkedList<>();

    public void rankChange(CrossKuangRank rank) {
        synchronized (this) {
            boolean change = false;
            boolean find = false;
            for (CrossKuangRank tmpRank : rankList) {
                // 找到了
                if (Objects.equals(tmpRank.getId(), rank.getId())) {
                    tmpRank.setValue(rank.getValue());
                    tmpRank.setParam(rank.getParam());
                    tmpRank.setTime(rank.getTime());
                    change = true;
                    find = true;
                    break;
                }
            }
            if (!find) {
                rankList.add(rank);
                change = true;
            }
            if (change) {
                rankSort();
            }
        }
    }

    public LinkedList<CrossKuangRank> getRankList() {
        return new LinkedList<>(rankList);
    }

    public void setRankList(LinkedList<CrossKuangRank> rankList) {
        synchronized (this) {
            this.rankList = rankList;
            rankSort();
        }
    }

    public int getMyRank(String id) {
        int rank = -1;
        int index = 0;
        synchronized (this) {
            for (CrossKuangRank userRank : rankList) {
                if (userRank.getId().equals(id)) {
                    rank = index + 1;
                    break;
                }
                index++;
            }
        }
        return rank;
    }

    /**
     * 排序，记得加锁
     */
    private void rankSort() {
        rankList.sort(rankSort);
    }
}
